package org.abettor.util.https;

import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;

import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocketFactory;

import org.abettor.util.security.cert.X509TrustAll;

/**
 * 用于创建 HTTPS 连接
 * @author <a href="http://www.abettor.org/" target="_blank">abettor</a>
 * @deprecated
 */
public class HttpsConnection
{
	/**
	 * 私有构造函数，不支持类的实例化操作
	 */
	private HttpsConnection()
	{
	}

	/**
	 * 与服务器建立 HTTPS 连接
	 * @param requestUrl 请求连接的绝对 URL 字符串
	 * @return 返回已经创建的 HTTPS 连接，失败返回 null。
	 */
	public static HttpsURLConnection getHttpsConnection(String requestUrl)
	{
		X509TrustAll [] trustManagers = { new X509TrustAll() };
		SecureRandom secureRandom = new SecureRandom();
		SSLContext sslContext = null;
		
		try
		{
			sslContext = SSLContext.getInstance("SSL");
			sslContext.init(null, trustManagers, secureRandom);
		}
		catch (NoSuchAlgorithmException e)
		{
			e.printStackTrace();
			return null;
		}
		catch (KeyManagementException e)
		{
			e.printStackTrace();
			return null;
		}

		URL url = null;
		HttpsURLConnection httpsConn = null;
		try
		{
			url = new URL(requestUrl);
			httpsConn = (HttpsURLConnection) url.openConnection();
		}
		catch (MalformedURLException e)
		{
			e.printStackTrace();
			return null;
		}
		catch (IOException e)
		{
			e.printStackTrace();
			return null;
		}

		SSLSocketFactory sslSocketFactory = sslContext.getSocketFactory();
		httpsConn.setSSLSocketFactory(sslSocketFactory);

		return httpsConn;
	}
}
